/*
 * @Author: kanglang
 * @Date: 2020-11-10 09:57:40
 * @LastEditors: zeki mini
 * @LastEditTime: 2021-05-24 17:15:31
 * @Description: 微信登录方法,按实际情况更改登录接口及保存数据
 */

import { NativeModules } from 'react-native';
import baseConfig from '@/config/baseConfig';
import user from '@/api/user';
import { msg, _, } from '@/common';
import { EventEmitter } from 'events';
import * as Wechat from './wechat';

const { wechatObj } = baseConfig;

export function WXLogin(callBack) {
  // 判断微信是否安装
  Wechat.isWXAppInstalled().then((isInstalled) => {
    if (isInstalled) {
      // 发送授权请求
      Wechat.sendAuthRequest(wechatObj.scope, wechatObj.state)
        .then((responseCode) => {
          // 返回code码，通过code获取access_token
          getAccessToken(responseCode.code, callBack);
        })
        .catch(() => {
          NativeModules.WindowModule.showWindow(
            { content: '登录授权发生错误', onlyRightBtn: '1' },
            () => { },
          );
        });
    } else {
      NativeModules.WindowModule.showWindow(
        {
          content: '没有安装微信,请先安装微信客户端在进行登录',
          onlyRightBtn: '1',
        },
        () => { },
      );
    }
  });
}

export function getAccessToken(data, callBack) {
  const url = wechatObj.wxBasicUrl + data + wechatObj.wxProfixUrl;
  fetch(url)
    .then((response) => response.json())
    .then((responseData) => {
      user
        .weixinLogin({
          accessToken: responseData.access_token,
          openid: responseData.openid,
        })
        .then((res) => {
          if (res.success) {
            callBack && callBack(true);
          } else if (res.msg === 'not') {
            msg.emit('router: goToNext', {
              routeName: 'MobileBind',
            });
          } else {
            msg.emit('app:tip', { text: res.msg ? res.msg : '连接服务器失败' });
          }
        })
        .catch(() => {
          NativeModules.WindowModule.showWindow(
            { content: '微信登录失败', onlyRightBtn: '1' },
            () => { },
          );
        });
    });
}

getAR = (code) => {
  return homeApi.getTextProtol({ code });
};
